package cn.edu.cqupt.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.edu.cqupt.core.JobsConstants;
import cn.edu.cqupt.core.MD5Encrypt;
import cn.edu.cqupt.core.PageParam;
import cn.edu.cqupt.core.UUIDFactory;
import cn.edu.cqupt.model.Activity;
import cn.edu.cqupt.model.Admirerecord;
import cn.edu.cqupt.model.CUser;
import cn.edu.cqupt.model.Classachievement;
import cn.edu.cqupt.model.Classnews;
import cn.edu.cqupt.model.Comments;
import cn.edu.cqupt.model.CommentsPage;
import cn.edu.cqupt.model.HeartwordPage;
import cn.edu.cqupt.model.Heartwords;
import cn.edu.cqupt.model.Member;
import cn.edu.cqupt.model.Personachievement;
import cn.edu.cqupt.service.HomeService;

@Controller
public class HomeController extends BaseController {
	
	private String visitorid="0000000000";

	private static Logger logger = LoggerFactory.getLogger(HomeController.class);
	@Value("upload_files")
	private String upload;
	@Resource
	private HomeService homeService;

	public HomeService getHomeService() {
		return homeService;
	}

	public void setHomeService(HomeService homeService) {
		this.homeService = homeService;
	}

	@RequestMapping("/index")
	public String Index(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session.getAttribute("change") == null || "null".equals(session.getAttribute("change"))) {
			session.setAttribute("change", 0);
		}
		// 获取首页班级成果展示区的四条最新班级荣誉
		List<Classachievement> ca = homeService.selectnewClassachieves();
		//获取首页新闻版块最新的三条
		List<Classnews> news=homeService.selectNews();
		session.setAttribute("CA", ca);
		session.setAttribute("news", news);
		return "index";
	}

	@RequestMapping("/yqlj")
	public String toyqlj() {
		return "links";
	}
	/**
	 * 导航栏跳转方法，跳转到心情墙
	 * 
	 * @return mood
	 */
	@RequestMapping("/xqq")
	public String toxqq(HttpServletRequest request) {
		//根据点赞数获取最热门的五条留言,页面上面显示的留言信息由获取分页数据的方法获得
		HttpSession session=request.getSession();
		List<HeartwordPage> list=homeService.selectPopularWords();
		session.setAttribute("popword", list);
		return "mood";
	}
	/**
	 * 获取心情墙的页面分页数据
	 * @return json数据
	 */
	@ResponseBody
	@RequestMapping("/getwords")
	public PageParam<HeartwordPage> getallHeartwordsBypage( @RequestParam(value = "page", required = false, defaultValue = "1") int currPage,
			HttpServletRequest request){
		   HttpSession session=request.getSession();
		   CUser user=(CUser) session.getAttribute("user");
		   String userid="";
		   if (user==null)
			   userid="null";
		   else userid=user.getUserid();
          int rowCount=homeService.selectHeartWordsCount();
          PageParam<HeartwordPage> pageParam=new PageParam<>();
          pageParam.setRowCount(rowCount);
  		if (pageParam.getTotalPage() > 0 && pageParam.getTotalPage() < currPage) {
  			currPage = pageParam.getTotalPage();
  		}
  		pageParam.setCurrPage(currPage);
		pageParam.setPageSize(10);
		pageParam=homeService.selectHeartwordsBypage(pageParam,userid);
		return pageParam;
	}
	
	/**
	 * 说说的点赞的功能，这里没有处理高并发问题
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/admire")
	public HashMap<String, Object> admire(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value="heartwordid" ,required=false,defaultValue="null")String id) {
		HashMap<String, Object>json=new HashMap<>();
		boolean admire=true;//前台图片是否可点
		String message="";
		String clicknum="";
		HttpSession session=request.getSession();
		CUser user=(CUser) session.getAttribute("user");
		if (user==null){
			message="亲，未登录或者不是班级成员，就不能进行点赞噢！！";
		}
		else {
		if (id.equals("null")){
			message="未知错误！！！";
			}
		else {
			boolean fix=true;
			List<Admirerecord> records=homeService.selectRecordByheartid(id);
			if (records!=null){
			for (Admirerecord red:records){
				if (red.getUserid().equals(user.getUserid()))
				fix=false;//该用户已经对此说说点赞
				}
			}
			
			if (fix){//该用户未对此条说说点赞，则修改数据库中的值
				Admirerecord record=new Admirerecord();
				record.setAdmireid((String)UUIDFactory.generateUUID());
				record.setCreatetime(new Date());
				record.setHeartwordid(id);
				record.setUserid(user.getUserid());
			int res=homeService.updateClicknums(record);//同时修改点赞数和用户点赞记录表	
			if (res>0){
				message="亲，点赞成功了噢！";
				admire=false;
			}
			else message="未知错误！！";
		}
		else {
			message="您已经点赞过了，不能再点赞了喔";
		}	
		}
		}
		clicknum=homeService.selectClicknumByid(id);
		json.put("admire", admire);
		json.put("message", message);
		json.put("clicknum", clicknum);
		
		return json;
	}
	
	/**
	 * 用户评论说说的方法
	 * @return json（状态值，信息）
	 */
	@ResponseBody
	@RequestMapping("/discuss")
	public HashMap<String, Object> discuss(@RequestParam(value="heartwordid",required=false,defaultValue="null")String heartwordid
			,@RequestParam(value="comment",required=false,defaultValue="null") String comment,
			HttpServletRequest request){
		HttpSession session=request.getSession();
		CUser user=(CUser) session.getAttribute("user");
		Member mem=(Member)session.getAttribute("member");
		boolean success=false;
		String message="";
		SimpleDateFormat bartDateFormat=new SimpleDateFormat("yy-MM-dd");//定制页面时间格式
		CommentsPage cop=new CommentsPage();//评论成功之后返回评论用户的信息
		if (heartwordid.equals("null")||comment.equals("null")){
			message="未知错误";
		}
		else {
			Comments com=new Comments();
			if (user==null){
				//该用户是游客或者未登录，都视为游客
				com.setComment(comment);
				com.setCommentid((String)UUIDFactory.generateUUID());
				com.setCreatetime(new Date());
				com.setHeartid(heartwordid);
				com.setUserid(visitorid);//存放游客的id
				int res=homeService.insertComment(com);
				if (res>0){
					cop.setComment(comment);
					cop.setCommentid(com.getCommentid());
					cop.setCreatetime(bartDateFormat.format(com.getCreatetime()));
					cop.setMembername("游客");
					cop.setPhoto("img/default/visitor.jpg");
					cop.setUserid(com.getUserid());
					message="亲！评论成功了！";
					success=true;
				}
				else message="亲！系统繁忙，请稍后再试！";
				}
			else {//评论的用户是登录的用户
				com.setComment(comment);
				com.setCommentid((String)UUIDFactory.generateUUID());
				com.setCreatetime(new Date());
				com.setHeartid(heartwordid);
				com.setUserid(user.getUserid());
				int res=homeService.insertComment(com);
				if (res>0){
					cop.setComment(comment);
					cop.setCommentid(com.getCommentid());
					cop.setCreatetime(bartDateFormat.format(com.getCreatetime()));
					cop.setMembername(mem.getMembername());
					cop.setPhoto(mem.getPhoto());
					cop.setUserid(user.getUserid());
					message="亲！评论成功了！";
					success=true;
				}
				else message="亲！系统繁忙，请稍后再试！";
			}
		}
		HashMap<String, Object>json=new HashMap<>();
		json.put("success", success);//值为true则刷新页面，false则不做任何操作，让用户检查页面
		json.put("message", message);//给用户的相应操作结果的提示信息
		json.put("comment", cop);
	    return json;	
	}
	@ResponseBody
	@RequestMapping("/delcomment")
	public HashMap<String, Object> delComment(@RequestParam(value="commentid",required=false,defaultValue="null")String commentid,
			@RequestParam(value="userid",required=false,defaultValue="null")String userid,
			HttpServletRequest request){
		String message="";
		boolean success=false;
		if (commentid.equals("null")||userid.equals("null")){
			message="未知错误！！";
		}
		else {
			HttpSession session=request.getSession();
			CUser user=(CUser)session.getAttribute("user");
			if (user!=null&&(user.getUserid().equals(userid)||user.getUsertype().equals("A"))){//是该用户自己发表的评论,或者此人是管理员，则可以删除
				int res=homeService.deleteComments(commentid);
				if (res>0){
					message="亲！删除成功了";
					success=true;
				}
				else message="未知错误！";
				
			}
			else message="亲！您没有权限删除该条评论！";
		}
		
		HashMap<String, Object> json=new HashMap<>();
		json.put("success", success);
		json.put("message", message);
		return json;
	}
	@ResponseBody
	@RequestMapping("/delword")
	public HashMap<String, Object> delHeartWord(
			@RequestParam(value="heartwordid",required=false,defaultValue="null")String heartwordid,
			@RequestParam(value="userid",required=false,defaultValue="null")String userid,
			HttpServletRequest request){
		System.out.println("heartwordid>>>>>>>>>>+"+heartwordid);
		System.out.println("userid>>>>>>>>>>>>>>>>"+userid);
		String message="";
		boolean success=false;
		if (heartwordid.equals("null")||userid.equals("null")){
			message="未知错误！";
		}
		else {
			HttpSession session =request.getSession();
			CUser user=(CUser) session.getAttribute("user");
			if (user==null||!(user.getUserid().equals(userid)||user.getUsertype().equals("A"))){
				//该说说不是此人发布的,或者此人是游客，并且此人也不是管理员，不能删除
				message="亲！您没有权限删除此条心情！！";
			}
			else {
				int res=homeService.deleteWordAndComments(heartwordid);
				if (res>0){
					message="亲！删除成功了，欢迎您继续在这里留下您的足迹！";
					success=true;
				}
			else message="服务器繁忙！请稍后再试！";
			}	
		}
		HashMap<String, Object>json=new HashMap<>();
		json.put("success", success);
		json.put("message", message);
		return json;
	}
	
	/**
	 * 导航栏跳转方法，跳转到兄弟姐妹
	 * 
	 * @return xdjm
	 */
	@RequestMapping("xdjm")
	public String toxdjm(HttpServletRequest request) {
		/*
		HttpSession session=request.getSession();
		//将所有班级成员的个人信息发送给前端
		List <Member> members=homeService.selectallMembers();
		session.setAttribute("members", members);
		*/
		return "siblings";
	}
	/**
	 * 获得所有的班级成员详细信息
	 * @return json数据
	 */
	@ResponseBody
	@RequestMapping("/index/getallM")
	public List<Member> getallMembers() {
		
	List <Member> members=homeService.selectallMembers();
	
		for (int i=1;i<=22;i++){
			Member mem=new Member();
			mem.setMemberid(Integer.toBinaryString(i));
			mem.setPhoto("img/test/"+i+".jpg");
			mem.setMembername("小"+i);
			members.add(mem);
		}
		
		return members;
	}

	@RequestMapping("/showMemInfo")
	public String showMemberInfo(@RequestParam(value="memberid",required=false,defaultValue="null") String memberid,
			HttpServletRequest request){
		HttpSession session=request.getSession();
		//用户点击一张照片，显示成员具体信息
		Member mem=homeService.selectMemberInfoByid(memberid);
		session.setAttribute("mem", mem);
		return "person";
	}

	/**
	 * 导航栏跳转方法，跳转到照片墙
	 * 
	 * @return zpq
	 */
	@RequestMapping("zpq")
	public String tozpq() {

		return "zpq";
	}

	/**
	 * 导航栏跳转功能，跳转到近期活动
	 * 
	 * @return
	 */
	@RequestMapping("/jqhd")
	public String tojqhd(HttpServletRequest request) {
		HttpSession session=request.getSession();
		List<Activity> acs=homeService.selectActivitiesBypage();
		Activity ac=null;
		if (acs==null)
		{
			ac.setActivitytime("2016年0月0日");
			ac.setCreater("adminstractor");
			ac.setEvent("在这里你会看见我们班级体近期开展的活动，我们收获了快乐、喜悦，同时我们也将这份收获分享给大家！");
			ac.setPicture("/img/default.png");
			ac.setTitle("爱我班级！");
			}
		else ac=acs.get(0);
		session.setAttribute("activities", acs);
		session.setAttribute("activity", ac);
		return "activity";
	}

	/**
	 * 首页中关于我们页面的跳转方法
	 * 
	 * @return
	 */
	@RequestMapping("/aboutus")
	public String aboutus() {
		return "Aboutus";
	}

	/**
	 * 根据传来的newid获取想要查看新闻的详细信息
	 * @return 展示页面
	 */
	@RequestMapping("/getdetailofnews")
	public String getDetailofnews(Model model,
			@RequestParam("newid") String newid){
		Classnews news=homeService.selectNewsByid(newid);
		model.addAttribute("oneNew", news);
		return "announcement";
	}

	/**
	 * 页面注销方法
	 * 
	 * @return
	 */
	@RequestMapping("/outlogin")
	public String outlogin(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		session.removeAttribute("member");
		session.setAttribute("change", 0);
		return "redirect:/index.do";
	}

	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String indexlogin(@RequestParam(value = "username", required = false, defaultValue = "null") String username,
			@RequestParam(value = "password", required = false, defaultValue = "null") String password,
			HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		/**
		 * @RequestParam(value="username", required=false, defaultValue="null")
		 *                                 String username,
		 * @RequestParam(value="password", required=false, defaultValue="null")
		 *                                 String password,
		 * @RequestParam(value="remberMe", required=false, defaultValue="up")
		 *                                 String remberMe,
		 */
		String remberMe = "on";
		int change = 0;
		int manage=-1;//用来控制三种班委显示的管理按钮。0表示宣传委员，给出管理新闻的权限；
		//1表示学习委员，给出管理荣誉的权限；2表示团支书，给出管理班级活动的权限
		String flagTips = "登录成功！";
	    String flagUrl ="";
		String url=request.getHeader("Referer");
		url=url.substring(url.lastIndexOf("CLASS"));
		//url=url.substring(url.lastIndexOf("8080"));//服务器上面由于访问路径没有项目名，所以需要这样截取
		//url=url.substring(5);
		url=url.substring(6);
		if(url.equals("")){
		 flagUrl  = "redirect:/index.do";
		}
		else 
		flagUrl  = "redirect:"+url;
		/**
		 * 进行判断，防止盗链 if(request.getHeader("Referer") == null ||
		 * "null".equalsIgnoreCase(request.getHeader("Referer"))) { flagTips =
		 * "请求非法！"; logger.error(flagTips); } else
		 */
		if ("null".equals(username) || "null".equals(password)) {
			flagTips = "用户名或密码为必填！";
		} else {
			HashMap<String, Object> loginuser = null;
			CUser user = null;
			Member member = null;
			try {
				loginuser = homeService.selectmemberByuserid(username,MD5Encrypt.makeMD5(password));
				user = (CUser) loginuser.get("user");
				member = (Member) loginuser.get("member");
			} catch (Exception e) {
				// 登录信息出错，返回状态码，主页页面不用改变
				HttpSession session = request.getSession(false);
				session.setAttribute("change", change);
				// 捕获到异常，说明登录用户信息不对
				redirectAttributes.addFlashAttribute("errorInfo", ShowTips(e.getMessage(), Color.WARN));
				// 此时flagUrl中记录的是主页位置，重新定位到主页
				return flagUrl;

				// return "error-404";
			}
			// 提示前端更改登录栏的显示样式
			if(user.getUsertype().equals("A"))
				change=2;//控制管理员的显示界面
			else change = 1;//控制普通用户的用户界面
			//给每个班委分配不同的权限
			switch (user.getUsertype()) {
			case "X": manage=0;
			break;
			case "T":manage=1;
			break;
			default:manage=2;
				break;
			}
			// 用户存在，且登录信息正确
			logger.info("#-TSJ-####-warn-######-用户:" + username + ":登陆成功！登陆类别:" + user.getUsertype());
			HttpSession session = request.getSession(false);
			// session超出时间(秒)
			session.setAttribute("change", change);
			session.setAttribute("manage", manage);
			session.setMaxInactiveInterval(JobsConstants.SESSION_DATE);
			session.setAttribute("user", user);
			session.setAttribute("member", member);

			// 是否设置【记住我】
			
			if ("on".equalsIgnoreCase(remberMe)) {
				logger.info("#-TSJ-####-warn-######-用户:" + username + "记住登陆");
				setCookie(request, response, username, MD5Encrypt.makeMD5(password),user.getUsertype());
			}
		}
		
		System.out.println(flagTips);
		redirectAttributes.addFlashAttribute("errorInfo", ShowTips(flagTips, Color.WARN));
		return flagUrl;
	}

	// 设置cookie的公用方法
	public void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String MD5passw,String userType) {
		Cookie cookie1 = new Cookie("username", name);
		Cookie cookie2 = new Cookie("password", MD5passw);
		Cookie cookie3=new Cookie("usertype",userType);
		// 为两个 Cookies 设置过期日期为 24 小时后
		cookie1.setMaxAge(JobsConstants.COOKIE_DATE);
		cookie2.setMaxAge(JobsConstants.COOKIE_DATE);
		cookie3.setMaxAge(JobsConstants.COOKIE_DATE);
		// 在响应头中添加两个 Cookies
		response.addCookie(cookie1);
		response.addCookie(cookie2);
		response.addCookie(cookie3);
	}

	/**
	 * 上传相册的公用方法
	 * 
	 * @return
	 */
	@RequestMapping("/upload")
	public String uploadphotos() {
		return null;
	}

	/**
	 * 修改密码的方法
	 * 
	 * @return
	 */
	@RequestMapping(value="/fixpassword",method=RequestMethod.POST)
	public String fixPassword(
			@RequestParam(value = "password", required = false, defaultValue = "null") String password,
			@RequestParam(value = "newpassword", required = false, defaultValue = "null") String newpassword,
			@RequestParam(value = "email", required = false, defaultValue = "null") String email,
			@RequestParam(value = "phone", required = false, defaultValue = "null") String phone,
			HttpServletRequest request,RedirectAttributes redirectAttributes) {	
		String url=request.getHeader("Referer");
		url=url.substring(url.lastIndexOf("CLASS"));
		url=url.substring(6);
		//url=url.substring(url.lastIndexOf("8080"));//服务器上面的路径没有项目名
		//url=url.substring(5);
		String flagUrl = "redirect:"+url;
		HttpSession session=request.getSession();
		CUser user=(CUser) session.getAttribute("user");
		if(MD5Encrypt.makeMD5(password).equals(user.getPassword())){
			user.setEdittime(new Date());
			if(!email.equals("null"))
			user.setEmail(email);
			user.setPassword(MD5Encrypt.makeMD5(newpassword));
			if (!phone.equals("null"))
			user.setPhone(phone);
			int res=homeService.updatepassword(user);
			if (res==0){
				redirectAttributes.addFlashAttribute("returnInfo", ShowTips("亲！修改密码操作失败！！", Color.WARN));
				return flagUrl;
			}
			redirectAttributes.addFlashAttribute("returnInfo", ShowTips("亲！修改密码成功了噢！！", Color.INFO));
			session.setAttribute("user", user);
			return flagUrl;
		}
		redirectAttributes.addFlashAttribute("returnInfo", ShowTips("亲！原密码有误！！", Color.WARN));
		return flagUrl;
	}

	/**
	 * 修改个人信息
	 */
	@RequestMapping(value="/fixinfo",method=RequestMethod.POST)
	public String fixmemberinfo(
			@RequestParam(value = "membername", required = false, defaultValue = "null") String membername,
			@RequestParam(value = "qq", required = false, defaultValue = "null") String qq,
			@RequestParam(value = "weixing", required = false, defaultValue = "null") String weixing,
			@RequestParam(value = "weibo", required = false, defaultValue = "null") String weibo,
			@RequestParam(value = "motto", required = false, defaultValue = "null") String motto,
			@RequestParam(value = "introduce", required = false, defaultValue = "null") String introduce,
			@RequestParam(value="file",required=false) MultipartFile file,
			HttpServletRequest request,RedirectAttributes redirectAttributes) {
		String url=request.getHeader("Referer");
		url=url.substring(url.lastIndexOf("CLASS"));
		//url=url.substring(url.lastIndexOf("8080"));
		url=url.substring(6);
		//url=url.substring(5);
		String flagUrl = "redirect:"+url;
		HttpSession session =request.getSession();
		Member member=(Member) session.getAttribute("member");
		CUser user=(CUser) session.getAttribute("user");
		Member mem=new Member();
		if (member==null){
			//用户没有修改过个人信息
			mem.setMemberid((String)UUIDFactory.generateUUID());
			mem.setUserid(user.getUserid());
			member.setPhoto("/img/default/member.jpg");
		}
		else {
		mem.setMemberid(member.getMemberid());
		mem.setUserid(member.getUserid());
		}
		//上传的照片非空就将照片路径存放到数据库中
		if (file!=null)
		{
			System.out.println("文件不是空的。。。。。。。");
		ServletContext sc = request.getSession().getServletContext();
		String dir = sc.getRealPath(upload);
		String basepath=dir+"/memberphotos";
			String originalFileName = file.getOriginalFilename();
			System.out.println("originalFileName......"+originalFileName);
			String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
			String filename=(String)UUIDFactory.generateUUID();
			String FileName=filename+ext;
			File targetFile=new File(basepath,FileName);
			if (!targetFile.exists()){
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				logger.error("公司联系人头像上传异常", e);
			}
			mem.setPhoto(upload+"/memberphotos/"+FileName);
		}
		else mem.setPhoto(member.getPhoto());
		//下面对页面传入的每个进行非空检验，如果是空的则用session中获取的member值
		if (membername.equals("null"))
			mem.setMembername(member.getMembername());
		else mem.setMembername(membername);
		
		if (qq.equals("null"))
			mem.setQq(member.getQq());
		else mem.setQq(qq);
		
		if (weixing.equals("null"))
			mem.setWeixing(member.getWeixing());
		else  mem.setWeixing(weixing);
		
		if (weibo.equals("null"))
			mem.setWeibo(member.getWeibo());
		else  mem.setWeibo(weibo);
		
		if (motto.equals("null"))
			mem.setMotto(member.getMotto());
		else mem.setMotto(motto);
		
		if (introduce.equals("null"))
			mem.setIntroduce(member.getIntroduce());
		else mem.setIntroduce(introduce);
		
		int res = homeService.updatememberselective(mem);
		if (res==0){
			redirectAttributes.addFlashAttribute("returnInfo", ShowTips("亲！修改个人信息未知错误！！", Color.WARN));
			return flagUrl;
		}
		redirectAttributes.addFlashAttribute("returnInfo", ShowTips("亲！修改个人信息成功了！！", Color.INFO));
		session.setAttribute("member", mem);
		return flagUrl;
	}

	/**
	 * 进入到个人荣誉的展示页面
	 * 
	 * @return 页面
	 */
	@RequestMapping("/index/toperson")
	public String topachievements(HttpServletRequest request,Model model) {
		//获取所有获奖人姓名放到查询框里面供用户进行选择查询
		List<String>names=new ArrayList<>();
		Set<String> set=new HashSet<>();
		names=homeService.selectallPersonnames();
		//去除重复的名字
		for (int a=0,b=names.size();a<b;a++){
			set.add(names.get(a));
		}
		int index = 0;
		Map<String,String> map = new HashMap<String,String>();
		Iterator<String> i=set.iterator();
		while (i.hasNext()){
			map.put(""+(index++),i.next());
		}
		model.addAttribute("names", map);
		HttpSession session=request.getSession();
		
		CUser user=(CUser) session.getAttribute("user");
		if (user!=null&&(user.getUsertype().equals("A")||user.getUsertype().equals("S"))){
			//学习委员和管理员都可以对荣誉进行管理
			return "personachievement";
		}
		return "userpersonachievement";
	}

	/**
	 * 进入到班级荣誉的展示页面
	 * 
	 * @return
	 */
	@RequestMapping("/index/toclass")
	public String toCachievements(HttpServletRequest request) {
		HttpSession session=request.getSession();
		CUser user=(CUser) session.getAttribute("user");
		if (user!=null&&(user.getUsertype().equals("A")||user.getUsertype().equals("S"))){
			return "classachievement";
		}
		return "userclassachievement";
	}
	/**
	 * 获取班级荣誉的展示数据
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/index/getallC")
	public PageParam<Classachievement> getallCachievements(
			@RequestParam(value = "page", required = false, defaultValue = "1") int currPage,
			@RequestParam(value = "rows", required = false, defaultValue = "10") int pageSize) {
		int rowCount = homeService.selectcountCachievements();
		PageParam<Classachievement> pageParam = new PageParam<>();
		pageParam.setRowCount(rowCount);
		if (pageParam.getTotalPage() > 0 && pageParam.getTotalPage() < currPage) {
			currPage = pageParam.getTotalPage();
		}
		pageParam.setCurrPage(currPage);
		pageParam.setPageSize(pageSize);
		pageParam = homeService.selectallCachievements(pageParam);
		return pageParam;
	}

	/**
	 * 获取个人荣誉页面的展示数据
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/index/getallp")
	public PageParam<Personachievement> getallpachievements(
			@RequestParam(value = "page", required = false, defaultValue = "1") int currPage,
			@RequestParam(value = "rows", required = false, defaultValue = "10") int pageSize,
			@RequestParam(value="personname",required=false,defaultValue="null")String personname) {
		PageParam<Personachievement> pageParam = new PageParam<>();
		if (personname.equals("null")){
		int rowCount = homeService.selectcountPachievements();
		pageParam.setRowCount(rowCount);
		if (pageParam.getTotalPage() > 0 && pageParam.getTotalPage() < currPage) {
			currPage = pageParam.getTotalPage();
		}
		pageParam.setCurrPage(currPage);
		pageParam.setPageSize(pageSize);
		pageParam = homeService.selectallPachievements(pageParam);
		return pageParam;
		}
		else {//获取用户的查询结果
			int rowcount=homeService.selectRowCountBypersonname(personname);
			pageParam.setRowCount(rowcount);
			if (pageParam.getTotalPage() > 0 && pageParam.getTotalPage() < currPage) {
				currPage = pageParam.getTotalPage();
			}
			pageParam.setCurrPage(currPage);
			pageParam.setPageSize(pageSize);
			pageParam=homeService.selectPByname(pageParam,personname);
			return pageParam;
		}
	}

	// @requestMapping("/admin/...")
	/**
	 * 下面全部是管理员对系统中的数据进行增删查改的方法
	 */

	/**
	 * 管理员对个人荣誉页面数据的增删改操作
	 * 
	 * @param request
	 * @param oper
	 *            对应三种操作值，del、add、edit
	 * @param id
	 *            删除的时候会前台传到后台的对象的id
	 * @param personachievementid
	 *            修改的时候前台传到后台的id
	 */
	@ResponseBody
	@RequestMapping("/admin/editPinfo")
	public HashMap<String, Object> etitPinfo(HttpServletRequest request,
			@RequestParam(value = "oper", required = false, defaultValue = "null") String oper,
			@RequestParam(value = "id", required = false, defaultValue = "null") String id,
			@RequestParam(value = "pricetime", required = false, defaultValue = "null") String pricetime,
			@RequestParam(value = "personname", required = false, defaultValue = "null") String personname,
			@RequestParam(value = "pricename", required = false, defaultValue = "null") String pricename,
			@RequestParam(value = "achievementlevel", required = false, defaultValue = "null") String achievementlevel,
			@RequestParam(value = "personachievementid", required = false, defaultValue = "null") String personachievementid) {
		Boolean success = false;
		String message = "";
		int res = 0;
		HttpSession session = request.getSession();
		CUser user = (CUser) session.getAttribute("user");
		if ("null".equalsIgnoreCase(oper)) {
			message = "未知错误！";
		} else if (null == user || !(user.getUsertype().equals("A")||user.getUsertype().equals("S"))) {
			message = "亲！您没有权限进行操作！！！！";
		} else {
			switch (oper) {
			case "del": {
				if ("null".equals(id)) {
					message = "未知错误！";
				} else {
					res = homeService.deletePachieve(id);
					if (res > 0) {
						message = "success";
						success = true;
					} else
						message = "数据库删除操作未知错误！";
				}
			}
				break;
			case "add": {
				Personachievement pa = new Personachievement();
				pa.setAchievementlevel(achievementlevel);
				pa.setCreatetime(new Date());
				pa.setPersonachievementid((String) UUIDFactory.generateUUID());
				pa.setPersonname(personname);
				pa.setPricetime(pricetime);
				pa.setStatus("1");
				pa.setPricename(pricename);
				int result = homeService.insertPachieve(pa);
				if (result == 0) {
					message = "添加个人荣誉记录失败！";
				}
				message = "success";
				success = true;
			}
				break;
			case "edit": {
				Personachievement pa = new Personachievement();
				pa.setAchievementlevel(achievementlevel);
				pa.setEdittime(new Date());
				pa.setPersonachievementid(personachievementid);
				pa.setPersonname(personname);
				pa.setPricename(pricename);
				pa.setPricetime(pricetime);
				res = homeService.updatePachieve(pa);
				if (res == 0) {
					message = "修改未知错误！！";
				}
				message = "success";
				success = true;
			}
				break;
			}

		}
		HashMap<String, Object> json = new HashMap<>();
		json.put("success", success);
		json.put("message", message);
		return json;
	}

	/**
	 * 管理员对班级荣誉页面数据的增删改操作
	 * 
	 * @param request
	 * @param oper
	 *            对应三种操作值，del、add、edit
	 * @param id
	 *            删除记录时前端传给后台的对象的id
	 * @param classachievementid
	 *            修改操作时前端传给后台的对象的id
	 */
	@ResponseBody
	@RequestMapping("/admin/editCinfo")
	public HashMap<String, Object> etitCinfo(HttpServletRequest request,
			@RequestParam(value = "oper", required = false, defaultValue = "null") String oper,
			@RequestParam(value = "id", required = false, defaultValue = "null") String id,
			@RequestParam(value = "pricetime", required = false, defaultValue = "null") String pricetime,
			@RequestParam(value = "achievementname", required = false, defaultValue = "null") String achievementname,
			@RequestParam(value = "achievementlevel", required = false, defaultValue = "null") String achievementlevel,
			@RequestParam(value = "price", required = false, defaultValue = "null") String price,
			@RequestParam(value = "classachievementid", required = false, defaultValue = "null") String classachievementid) {
		Boolean success = false;
		String message = "";
		int res = 0;
		HttpSession session = request.getSession();
		CUser user = (CUser) session.getAttribute("user");
		if ("null".equalsIgnoreCase(oper)) {
			message = "未知错误！";
		} else if (null == user || !(user.getUsertype().equals("A")||user.getUsertype().equals("S"))) {
			message = "亲！您没有权限进行操作！！！！";
		} else {
			switch (oper) {
			case "del": {
				if ("null".equals(id)) {
					message = "未知错误！";
				} else {
					res = homeService.deleteCachieve(id);
					if (res > 0) {
						message = "success";
						success = true;
					} else
						message = "数据库删除操作未知错误！";
				}
			}
				break;
			case "add": {
				Classachievement ca = new Classachievement();
				ca.setAchievementlevel(achievementlevel);
				ca.setAchievementname(achievementname);
				ca.setClassachievementid((String) UUIDFactory.generateUUID());
				ca.setCreatetime(new Date());
				ca.setPrice(price);
				ca.setPricetime(pricetime);
				ca.setStatus("1");
				int result = homeService.insertCachieve(ca);
				if (result == 0) {
					message = "添加个人荣誉记录失败！";
				}
				message = "success";
				success = true;
			}
				break;
			case "edit": {
				Classachievement ca = new Classachievement();
				ca.setAchievementlevel(achievementlevel);
				ca.setAchievementname(achievementname);
				ca.setClassachievementid(classachievementid);
				ca.setEdittime(new Date());
				ca.setPrice(price);
				ca.setPricetime(pricetime);
				res = homeService.updateCachieve(ca);
				if (res == 0) {
					message = "修改未知错误！！";
				}
				message = "success";
				success = true;
			}
				break;
			}

		}
		HashMap<String, Object> json = new HashMap<>();
		json.put("success", success);
		json.put("message", message);
		return json;
	}
	
	/**
	 * 页面上管理新闻（对管理员可见）按钮的跳转方法，先跳转到表格页面，再通过json传值
	 */
	@RequestMapping("/admin/manageNews")
	public String manageNews(){
		return "mangenews";
	}
	@RequestMapping("/admin/getallNews")
	@ResponseBody
	public PageParam<Classnews> getallNews(
			@RequestParam(value = "page", required = false, defaultValue = "1") int currPage,
			@RequestParam(value = "rows", required = false, defaultValue = "10") int pageSize) {
		int rowCount=homeService.selectNewsCount();
		PageParam<Classnews>pageParam=new PageParam<>();
		pageParam.setRowCount(rowCount);
		if (pageParam.getTotalPage() > 0 && pageParam.getTotalPage() < currPage) {
			currPage = pageParam.getTotalPage();
		}
		pageParam.setCurrPage(currPage);
		pageParam.setPageSize(pageSize);
		pageParam=homeService.selectallNewsBypage(pageParam);
		return pageParam;
	}
	/**
	 * 添加按钮跳转方法
	 * @return 管理员添加新闻页面
	 */
	@RequestMapping("/admin/addnewsindex")
	public String addnewsindex(){
		return "addNews";
	}
	/**
	 * 管理员添加新闻方法
	 * @param creater
	 * @param newstime
	 * @param title
	 * @param event
	 * @param file
	 * @param redirectAttributes 携带提示信息
	 * @return 表格管理页面
	 */
	@RequestMapping(value="/admin/addnews",method=RequestMethod.POST)
	public String addnews(
			@RequestParam(value = "creater", required = false, defaultValue = "null") String creater,
			@RequestParam(value = "newstime", required = false, defaultValue = "null") String newstime,
			@RequestParam(value = "title", required = false, defaultValue = "null") String title,
			@RequestParam(value = "event", required = false, defaultValue = "null") String event,
			@RequestParam("file") MultipartFile file,
			HttpServletRequest request,RedirectAttributes redirectAttributes){
		HttpSession session=request.getSession();
		Classnews news=new Classnews();
		if (file!=null)
		{
		ServletContext sc = request.getSession().getServletContext();
		String dir = sc.getRealPath(upload);
		String basepath=dir+"/newspictures";
			String originalFileName = file.getOriginalFilename();
			String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
			String filename=(String)UUIDFactory.generateUUID();
			String FileName=filename+ext;
			File targetFile=new File(basepath,FileName);
			if (!targetFile.exists()){
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				logger.error("上传新闻照片异常！！！", e);
			}
			news.setPicture(upload+"/newspictures/"+FileName);
		}
		else news.setPicture("/img/default/news.jpg");
		news.setCreater(creater);
		news.setCreatetime(new Date());
		news.setEvent(event);
		news.setNewid((String)UUIDFactory.generateUUID());
		news.setNewstime(newstime);
		news.setStatus("1");
		news.setTitle(title);
		int res=homeService.insertNews(news);
		if (res>0)
			session.setAttribute("returninfo", ShowTips("亲！添加新闻记录成功了噢！！！", Color.INFO));
		else 
			session.setAttribute("returninfo", ShowTips("亲！添加新闻记录失败了！！！，发生了未知错误！", Color.WARN));
			
		return "redirect:/admin/manageNews.do";
	}

	/**
	 * 管理员删除新闻
	 * @param newid
	 * @return json
	 */
	@ResponseBody
	@RequestMapping("/admin/delNews")
	public HashMap<String, Object> delNews(@RequestParam(value = "id", required = false, defaultValue = "null") String id,
			  HttpServletRequest request){
		HttpSession session=request.getSession();
		CUser user=(CUser) session.getAttribute("user");
		String message="";
		boolean success=false;
		if ("null".equals(id))
			message="未知错误！！！！！";
		else if (user==null||!(user.getUsertype().equals("A")||user.getUsertype().equals("X"))){
			message="亲！您没有权限进行该操作！！！";
		}
		else{
		int res=homeService.deleteNews(id);
		if (res>0){
			message="删除新闻成功！！";
			success=true;
		}
		else message="删除操作失败！！！！";
		}
		HashMap<String, Object> json = new HashMap<>();
		json.put("success", success);
		json.put("message", message);
		return json;
	}
	
	
	/**
	 * 管理管理活动表格页面跳转方法
	 * @return  表格页面
	 */
	@RequestMapping("/admin/manageAtindex")
	public String manageActivitiesindex(){
		return "mangeActivity";
	}
	
	@RequestMapping("/getdetailOfactivity")
	public String getdetailOfActivity(@RequestParam("activityid") String activityid,
			Model model) {
		Activity ac=homeService.selectActivity(activityid);
		model.addAttribute("ac", ac);
		return "showActivity";
	}
	/**
	 * 近期活动页面，展示侧边栏的具体活动信息
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/showActivity")
	public Activity showActivity(@RequestParam("activityid") String activityid) {
		Activity ac=homeService.selectActivity(activityid);
		return ac;
	}
	/**
	 * 获取管理表格页面的所有活动数据
	 * @param currPage
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/admin/getallActivities")
	@ResponseBody
	public PageParam<Activity> getallActivities(
			@RequestParam(value = "page", required = false, defaultValue = "1") int currPage,
			@RequestParam(value = "rows", required = false, defaultValue = "10") int pageSize) {
		int rowCount=homeService.selectActivityCount();
		PageParam<Activity>pageParam=new PageParam<>();
		pageParam.setRowCount(rowCount);
		if (pageParam.getTotalPage() > 0 && pageParam.getTotalPage() < currPage) {
			currPage = pageParam.getTotalPage();
		}
		pageParam.setCurrPage(currPage);
		pageParam.setPageSize(pageSize);
		pageParam=homeService.selectallActivityBypage(pageParam);
		return pageParam;
	}
	/**
	 * 管理员删除班级活动方法
	 * @param id  要删除的活动记录的id
	 * @param request
	 * @return  json状态值
	 */
	@ResponseBody
	@RequestMapping("/admin/delActivity")
	public HashMap<String, Object> delActivity(@RequestParam(value = "id", required = false, defaultValue = "null") String id,
			  HttpServletRequest request){
		HttpSession session=request.getSession();
		CUser user=(CUser) session.getAttribute("user");
		String message="";
		boolean success=false;
		if ("null".equals(id))
			message="未知错误！！！！！";
		else if (user==null||!(user.getUsertype().equals("A")||user.getUsertype().equals("T"))){
			message="亲！您没有权限进行该操作！！！";
		}
		else{
		int res=homeService.deleteAcitvityByid(id);
		if (res>0){
			message="删除操作成功！！";
			success=true;
		}
		else message="删除操作失败！！！！";
		}
		HashMap<String, Object> json = new HashMap<>();
		json.put("success", success);
		json.put("message", message);
		return json;
	}
	/**
	 * 管理员添加活动主页跳转方法
	 * @return  添加活动页面
	 */
	@RequestMapping("/admin/addActivityindex")
	public String addActivityindex() {
		return "addActivity";
	}
	/**
	 * 管理员添加新活动方法
	 * @param creater  活动添加人
	 * @param activitytime 活动开展时间
	 * @param title  活动主题或标题
	 * @param event 活动详情介绍
	 * @param file 活动照片
	 * @param request 
	 * @param redirectAttributes
	 * @return  对表格页面请求方法
	 */
	@RequestMapping(value="/admin/addAtivity",method=RequestMethod.POST)
	public String addActivity(
			@RequestParam(value = "creater", required = false, defaultValue = "null") String creater,
			@RequestParam(value = "activitytime", required = false, defaultValue = "null") String activitytime,
			@RequestParam(value = "title", required = false, defaultValue = "null") String title,
			@RequestParam(value = "event", required = false, defaultValue = "null") String event,
			@RequestParam("file") MultipartFile file,
			HttpServletRequest request,RedirectAttributes redirectAttributes){
		HttpSession session=request.getSession();
		Activity ac=new Activity();
		if (file!=null)
		{
		ServletContext sc = request.getSession().getServletContext();
		String dir = sc.getRealPath(upload);
		String basepath=dir+"/ActivityPictures";
			String originalFileName = file.getOriginalFilename();
			String ext = originalFileName.substring(originalFileName.lastIndexOf("."));
			String filename=(String)UUIDFactory.generateUUID();
			String FileName=filename+ext;
			File targetFile=new File(basepath,FileName);
			if (!targetFile.exists()){
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				logger.error("上传新闻照片异常！！！", e);
			}
			ac.setPicture(upload+"/ActivityPictures/"+FileName);
		}
		else ac.setPicture("/img/default/activity.png");
		ac.setCreater(creater);
		ac.setCreatetime(new Date());
		ac.setEvent(event);
		ac.setActivityid((String)UUIDFactory.generateUUID());
		ac.setActivitytime(activitytime);
		ac.setStatus("1");
		ac.setTitle(title);
		int res=homeService.insertActivity(ac);
		if (res>0)
			session.setAttribute("returninfo", ShowTips("亲！添加班级活动成功了噢！！！", Color.INFO));
		else 
			session.setAttribute("returninfo", ShowTips("亲！添加班级活动失败了！！！，发生了未知错误！", Color.WARN));
			
		return "redirect:/admin/manageAtindex.do";
	}
	
	/**
	 * 心情墙的相关方法
	 */
	/**
	 * 心情墙添加心情方法
	 * @param heartword
	 * @param request
	 * @return  json
	 */
	@ResponseBody
	@RequestMapping("/liuyan")
	public HashMap<String, Object> liuyan(@RequestParam(value="heartword",required=false,defaultValue="null") String heartword,
			HttpServletRequest request){
		HttpSession session=request.getSession();
		String message="";
		boolean success=false;
		HeartwordPage htp=new HeartwordPage();
		Heartwords word=new Heartwords();
		CUser user=(CUser)session.getAttribute("user");
		Member mem=(Member) session.getAttribute("member");
		
		if (!heartword.equals("null")){//用户输入了心情
		word.setClicknum(0);
		word.setCreatetime(new Date());
		word.setHeartword(heartword);
		word.setId((String)UUIDFactory.generateUUID());
		if (user==null){
			htp.setMembername("游客");
			htp.setPhoto("img/default/visitor.jpg");
			htp.setUserid(visitorid);
			word.setUserid(visitorid);
		}
		else {
		word.setUserid(user.getUserid());
		htp.setMembername(mem.getMembername());
		htp.setPhoto(mem.getPhoto());
		htp.setUserid(user.getUserid());
		}
		int res=homeService.insertHeartword(word);
		if (res>0){
			message="亲！发布心情成功了，您可以密切关注他人的评论约！";
			success=true;
			//将页面上面要显示的数据放到创建的vo对象中
			htp.setClicknum(word.getClicknum());
			SimpleDateFormat bartDateFormat=new SimpleDateFormat("yy-MM-dd");
			htp.setCreatetime(bartDateFormat.format(word.getCreatetime()));
			htp.setHeartword(heartword);
			htp.setId(word.getId());
		}
		else message="亲！系统繁忙，等会儿再试试吧！";
		}
		else message="请输入您的心情！！";
		HashMap<String, Object> json=new HashMap<>();
		json.put("message", message);
		json.put("success", success);
		json.put("htp", htp);
		return json;
	}
	
	
}
